<template>
  <a-modal
    :title="pop.title"
    :visible="visible"
    :maskClosable="false"
    :width="pop.width"
    @cancel="close"
    @ok="onPopSubmit"
    :confirmLoading="pop.loading"
  >
    <div class="ctr-box">
      <div class="skpz-search-address">
        <a-input-search
          placeholder="请输入地名"
          v-if="isStatus != 'view'"
          @search="onSearch"
          enterButton
          v-model="searchValue"
          allowClear
        />
        <div class="search-address-list" v-if="searchAddressList.length > 0 && searchListshow">
          <div
            class="search-address-name"
            v-for="(item, index) in searchAddressList"
            :key="index"
            @click="toMapAddress(item)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div style="position: absolute;left: 50%;top: 50%;z-index: 998;">
        <a-spin :spinning="searchLoading" tip="loading" size="large" />
      </div>
      <div style="display: flex;height: 60px;">
        <a-form layout="inline" :form="form" class="form-inline-vali">
          <a-form-item label="区域名称">
            <a-input
              :disabled="isStatus == 'view'"
              v-decorator="[
                'name',
                { initialValue: editForm.name, rules: [{ required: true, message: '区域名称不能为空！' }] }
              ]"
              placeholder="请输入区域名称"
            ></a-input>
          </a-form-item>
          <a-form-item label="区域类型">
            <j-dict-select-tag
              v-decorator="[
                'type',
                { initialValue: editForm.type, rules: [{ required: true, message: '区域类型不能为空！' }] }
              ]"
              :triggerChange="true"
              placeholder="请选择区域类型"
              style="width: 171px;"
              dictCode="area_type"
              :disabled="isStatus == 'view'"
            />
          </a-form-item>
        </a-form>
        <a-button
          type="danger"
          v-if="isStatus != 'view'"
          ghost
          class="r-clear"
          @click="removeOverlay"
        >清除已框选的区域</a-button
        >
      </div>
    </div>
    <div class="map" id="map_draw" style="height: 550px; background-color: #f7f7f7;"></div>
    <div class="leftBox" v-if="isStatus == 'view'">
      <!-- <Drawer
        ref="drawerId"
        :row="row"
        :visible="drawerShow"
        @closeDrawer="closeDrawer"
        @clickRow="onClickRow"
      ></Drawer> -->
      <div class="handle leftHandle" @click="clickLeft">
        <a-icon class="close-icon" type="right" title="展开" />
      </div>
    </div>
  </a-modal>
</template>

<script>
import * as api from '@/api/xlgc/areaEvent.js'
import * as eventModelApi from '@/api/xlgc/eventModel.js'
import '../../../../../public/offlinemap/tools/DrawingManager_min.css'
// import Drawer from './drawer'
import config from '@/defaultSettings'
export default {
  props: ['visible', 'row', 'isStatus', 'title', 'regionType'],
  components: {
    // Drawer
  },
  data() {
    return {
      pop: {
        title: '地图框选',
        isShow: false,
        loading: false,
        width: 1150
      },
      form: this.$form.createForm(this),
      editForm: {},
      map: null,
      overlays: [],
      searchValue: '',
      searchAddressList: [],
      MarkerList: '',
      searchLoading: false,
      searchListshow: false,
      chartStyleOptions: {
        strokeColor: '#1890FF', // 边线颜色。
        fillColor: '#1890FF', // 填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 2, // 边线的宽度，以像素为单位。
        strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
        fillOpacity: 0.3, // 填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' // 边线的样式，solid或dashed
      },
      drawerShow: false
    }
  },
  computed: {},
  watch: {
    visible(value) {
      if (value) {
        this.form = this.$form.createForm(this)
        this.editForm = {
          chartVOList: []
        }
        this.pop.loading = false
        this.$nextTick(() => {
          if (this.isStatus == 'add') {
            this.drawMap()
          } else {
            this.getDetail()
          }
        })
      }
    },
    title(value) {
      this.pop.title = value
    }
  },
  methods: {
    clickLeft() {
      this.drawerShow = true
    },
    closeDrawer() {
      this.drawerShow = false
    },
    onClickRow(row) {
      let obj = {
        chartVOList: [
          {
            latitude: row.latitude,
            longtitude: row.longtitude,
            radius: row.radius
          }
        ]
      }
      this.onChartVOList(obj)
    },
    onSearch() {
      // 搜索地址
      this.searchValue = this.searchValue.replace(/\s*/g, '')
      if (!this.searchValue) return false
      this.searchLoading = true
      // 参数：format=json&page_num=0&page_size=10&q=海口市&sq_type=bounds&bounds=19.754563,110.103888,20.123978,110.787787
      let params = { format: 'json', page_num: 0, page_size: 10, q: this.searchValue, sq_type: 'bounds' }
      api.getaddress(params).then(res => {
        this.searchLoading = false
        let str = res.data.replace(/\\/g, '')
        // console.log('str')
        // console.log(JSON.parse(str))
        let result = JSON.parse(str)
        // console.log(result)
        if (result.totalCount > 0) {
          this.searchAddressList = result.results
          if (this.searchAddressList.length == 1) {
            this.toMapAddress(this.searchAddressList[0])
            this.searchListshow = false
          } else {
            this.searchListshow = true
          }
        }
      })
    },
    toMapAddress(item) {
      console.log(item)
      let params = {
        longitude: item.location.lon,
        latitude: item.location.lat
      }
      // cgcs2000坐标系转换为百度地图坐标系
      eventModelApi.getCs2000ToBD09(params).then(res => {
        if (res.success) {
          // 搜索地址对应的位置
          let point = new BMap.Point(res.result.longitude, res.result.latitude)
          // let point = new BMap.Point(item.location.lon, item.location.lat)
          // let point = new BMap.Point('110.348873', '20.065681')
          this.map.removeOverlay(this.MarkerList)
          this.map.centerAndZoom(point, 16)
          this.map.enableScrollWheelZoom(true) // 可缩放
          this.MarkerList = new BMap.Marker(point)
          this.map.addOverlay(this.MarkerList)
          this.searchValue = item.name
          this.searchListshow = false
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    close() {
      this.$emit('on-close')
      return false
    },
    getDetail() {
      api
        .getDetailsById({ id: this.row.id })
        .then(res => {
          if (res.success) {
            let { name, type, chartVOList } = res.result
            this.editForm = {
              name,
              type,
              chartVOList
            }
            this.drawMap()
            this.onChartVOList(this.editForm)
            if (this.isStatus == 'view') {
              this.drawerShow = true
              let that = this
              setTimeout(() => {
                that.$refs.drawerId.refreshTable()
              }, 500)
            } else {
              this.drawerShow = false
            }
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    drawMap() {
      const _this = this
      _this.map = new BMap.Map('map_draw', { maxZoom: 18 })
      // _this.map.centerAndZoom(new BMap.Point(125.35, 43.88), 12)
      _this.map.centerAndZoom(new BMap.Point(config.initLng, config.initLat), 12)
      _this.map.enableScrollWheelZoom()

      // 绘制工具事件
      _this.overlays = []

      let overlaycomplete = function(e) {
        const drawMode = e.drawingMode
        _this.clearAll()
        _this.overlays.push(e.overlay)
        _this.editForm.chartVOList = []

        if (drawMode === 'circle') {
          // 圆形
          let circle = e.overlay
          let center = circle.getCenter()
          let radius = circle.getRadius()
          _this.editForm.chartVOList.push({
            longtitude: center.lng,
            latitude: center.lat,
            radius: radius.toString()
          })
        } else {
          // 多边形
          let path = e.overlay.getPath() // Array<Point> 返回多边型的点数组
          for (let i = 0; i < path.length; i++) {
            _this.editForm.chartVOList.push({ longtitude: path[i].lng, latitude: path[i].lat, radius: '' })
          }
        }
      }
      // 详情不需要框选工具
      if (this.isStatus != 'view') {
        // 实例化鼠标绘制工具
        _this.drawingManager = new BMapLib.DrawingManager(_this.map, {
          isOpen: false, // 是否开启绘制模式
          enableDrawingTool: true, // 是否显示工具栏
          drawingToolOptions: {
            anchor: window.BMAP_ANCHOR_TOP_RIGHT, // 位置
            offset: new BMap.Size(5, 5), // 偏离值
            drawingModes: [window.BMAP_DRAWING_POLYGON, window.BMAP_DRAWING_CIRCLE, window.BMAP_DRAWING_RECTANGLE]
          },
          circleOptions: _this.chartStyleOptions, // 圆的样式
          polylineOptions: _this.chartStyleOptions, // 线的样式
          polygonOptions: _this.chartStyleOptions, // 多边形的样式
          rectangleOptions: _this.chartStyleOptions // 矩形的样式
        })
        // 添加鼠标绘制工具监听事件，用于获取绘制结果
        _this.drawingManager.addEventListener('overlaycomplete', overlaycomplete)
      }
    },
    clearAll() {
      for (var i = 0; i < this.overlays.length; i++) {
        this.map.removeOverlay(this.overlays[i])
      }
      this.overlays.length = 0
    },
    removeOverlay() {
      this.map.clearOverlays()
      this.editForm.chartVOList = []
    },
    onPopSubmit() {
      if (this.isStatus == 'view') {
        this.close()
        this.pop.loading = false
      } else {
        this.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            if (this.editForm.chartVOList.length) {
              this.pop.loading = true
              this.editForm.regionType = this.regionType
              if (this.isStatus == 'edit') {
                this.editForm.id = this.row.id
                // 修改
                this.editForm.name = values.name
                this.editForm.type = values.type
                api
                  .updateByFrame(this.editForm)
                  .then(res => {
                    if (res.success) {
                      this.$message.success('修改成功！')
                      this.$emit('on-submit')
                      this.removeOverlay()
                      this.close()
                      this.pop.loading = false
                    } else {
                      this.pop.loading = false
                      this.$message.warning(res.message)
                    }
                  })
                  .catch(() => {
                    this.pop.loading = false
                    this.$forceUpdate()
                  })
              } else {
                // 添加
                let params = Object.assign(values, this.editForm)
                console.log('params', params)
                api
                  .createByFrame(params)
                  .then(res => {
                    if (res.success) {
                      this.$message.success('添加成功！')
                      this.$emit('on-submit')
                      this.removeOverlay()
                      this.close()
                      this.pop.loading = false
                    } else {
                      this.pop.loading = false
                      this.$message.warning(res.message)
                    }
                  })
                  .catch(() => {
                    this.pop.loading = false
                    this.$forceUpdate()
                  })
              }
            } else {
              this.$message.error(`请框选区域！`)
            }
          }
        })
      }
    },
    onChartVOList(obj) {
      let chartVOList = obj.chartVOList
      let point = []
      let chartObjet = null

      for (let i = 0, len = chartVOList.length; i < len; i++) {
        point.push(new BMap.Point(chartVOList[i].longtitude, chartVOList[i].latitude))
      }

      if (chartVOList.length > 1) {
        // 多边形
        chartObjet = new BMap.Polygon(point, this.chartStyleOptions)
      } else {
        // 圆形
        chartObjet = new BMap.Circle(point[0], chartVOList[0].radius, this.chartStyleOptions)
      }
      this.overlays = [chartObjet]
      this.map.addOverlay(chartObjet)
      this.map.panTo(point[0])
    }
  }
}
</script>
<style lang="less" scoped>
.ctr-box {
  // margin-bottom: 24px;
  .gutter-row {
    margin-bottom: 16px;
  }
  .r-clear {
    margin-top: 3px;
    // position: absolute;
    // right: 0;
    // margin-right: 30px;
    margin-left: 50px;
  }
}

.skpz-search-address {
  position: absolute;
  right: 27px;
  top: 147px;
  z-index: 999;
  width: 350px;
  .search-address-list {
    width: 302px;
    top: 38px;
    left: 0px;
    background-color: #fff;
    color: #aaa;
    font-size: 12px;
    height: 300px;
    overflow-y: scroll;
    .search-address-name {
      width: 100%;
      height: 30px;
      line-height: 30px;
      margin-left: 10px;
      border-bottom: 1px solid #d9d9d9;
      cursor: pointer;
    }
  }
}
/deep/.BMapLib_Drawing {
  // inset: 5px auto auto 5px !important;
  position: absolute !important;
  left: 5px !important;
  top: 5px !important;
}
.leftBox {
  overflow: hidden;
  position: absolute;
  left: 20px;
  top: 139px;
  height: 550px;
  width: 450px;
  .handle {
    position: absolute;
    display: inline-block;
    top: 0;
    z-index: 10;
    background: rgba(0, 0, 0, 0.6);
    height: 100%;
    cursor: pointer;
    transition: 0.5s;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .close-icon {
      font-size: 20px;
      color: #fff;
    }
    &.leftHandle {
      left: 0;
    }
    &.rightHandle {
      right: 0;
    }
  }
}
</style>
